package com.wangzhixuan.controller.common;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.filestorage.BaseFileStorageService;
import com.wangzhixuan.commons.filestorage.FileStorageEnum;
import com.wangzhixuan.commons.filestorage.FileStorageFactory;
import com.wangzhixuan.commons.filestorage.UploadResult;
import com.wangzhixuan.commons.result.Result;
import com.wangzhixuan.commons.shiro.ShiroUtils;
import com.wangzhixuan.commons.shiro.captcha.DreamCaptcha;
import com.wangzhixuan.commons.ueditor.UeditorService;
import com.wangzhixuan.model.SysFile;
import com.wangzhixuan.service.ISysFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 通用的控制器
 *
 * @author L.cm
 */
@Api("1. 公共接口")
@RestController
@RequestMapping("commons")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CommonsController extends BaseController {
    private final DreamCaptcha dreamCaptcha;
    private final UeditorService ueditorService;
    private final ISysFileService sysFileService;

    /**
     * 图形验证码
     */
    @ApiOperation("1. 图形验证码")
    @GetMapping(value = "captcha.jpg", produces = MediaType.IMAGE_JPEG_VALUE)
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        dreamCaptcha.generate(request, response);
    }

    /**
     * ueditor编辑器
     */
    @ApiIgnore
    @RequestMapping(value = "ueditor",produces = MediaType.TEXT_HTML_VALUE)
    public ResponseEntity<String> ueditor(HttpServletRequest request) {
        String json = ueditorService.exec(request,getDomain(), ShiroUtils.getUser());
        return ResponseEntity.ok(json);
    }

    /**
     * 从请求中获取文件
     *
     * @param request 请求
     * @return 上传结果
     */
    private List<MultipartFile> getRequestFiles(HttpServletRequest request) {
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        List<MultipartFile> files = new ArrayList<>(1);
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (resolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile multipartFile = multiRequest.getFile(iter.next());
                if (multipartFile != null && multipartFile.getSize() > 0) {
                    files.add(multipartFile);
                }
            }
            if (files.size() > 0) {
                return files;
            }
        }
        return null;
    }


    @ApiOperation("2. 多文件上传接口")
    @ApiOperationSupport(author = "lixin")
    @PostMapping("/uploadFile")
    @ApiImplicitParam(name = "file", value = "文件上传示例", paramType = "form", dataType = "__file")
    public Result<List<SysFile>> uploadFile(HttpServletRequest request) {
        List<MultipartFile> files = getRequestFiles(request);
        if (CollectionUtils.isNotEmpty(files)) {
            List<UploadResult> filesData = new ArrayList<>();
            files.forEach(file -> {
                BaseFileStorageService baseFileStorageService = FileStorageFactory.getService(FileStorageEnum.LOCAL);
                UploadResult result = baseFileStorageService.uploadFile(file);
                filesData.add(result);
            });
            return renderObj(sysFileService.saveFiles(filesData));
        } else {
            return renderError("请先上传文件");
        }

    }
}
